from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseForbidden, JsonResponse
from django import http
import re
from users.models import User
from django.db import DatabaseError
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from mdmall.utils.response_code import RETCODE


# 用户中心页面
def user_info_view(request):
    if not request.user.is_authenticated:
        return redirect('/users/login_view')
    else:
        return render(request, 'users/user_center_info.html')


# 注册页
def index(request):
    return render(request, 'users/register.html')


# 注册
def registered(request):
    # 接收参数
    username = request.POST['username']
    password = request.POST['password']
    password2 = request.POST['password2']
    mobile = request.POST['mobile']
    allow = request.POST['allow']
    # 校验参数
    # 判断参数是否齐全:all([列表])：会去校验列表中的元素是否为空，只要有一个为空，返回false
    if not all([username, password, password2, mobile, allow]):
        return HttpResponse('缺少必传参数')
    # 判断用户名是否是5-20个字符
    if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
        return HttpResponse('请输入5-20个字符的用户名')
    # 判断密码是否是8-20个数字
    if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
        return HttpResponse('请输入8-20位的密码')
    # 判断两次密码是否一致
    if password != password2:
        return HttpResponse('两次输入的密码不一致')
    # 判断手机号是否合法
    if not re.match(r'^1[3-9]\d{9}$', mobile):
        return HttpResponse('请输入正确的手机号码')
    # 判断是否勾选用户协议
    if allow != 'on':
        return HttpResponse('请勾选用户协议')
    # 保存数据
    try:
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
    except DatabaseError:
        return render(request, 'users/register.html', {'register_errmsg': '注册失败'})
    # 实现登录
    login(request, user)
    # 成功重定向
    return redirect('/home/index')


# 验证用户名是否重复
def count(request, username):

    # 实现主体业务逻辑：使用username查询对应的记录的条数(filter返回的是满足条件的结果集)
    count = User.objects.filter(username=username).count()
    # 响应结果
    return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


# 验证手机是否重复
def count_moblie(request, usermoblie):

    # 实现主体业务逻辑：使用username查询对应的记录的条数(filter返回的是满足条件的结果集)
    count = User.objects.filter(mobile=usermoblie).count()
    # 响应结果
    return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


# 登录
def login_view(request):
    return render(request, 'users/login.html')


# 检验登录
def login_check(request):
    username = request.POST['username']
    password = request.POST['password']
    remembered = request.POST.get('remembered')

    if not all([username, password]):
        return HttpResponse('缺少必要参数')

    # 判断用户名是否是5-20个字符
    if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
        return HttpResponse('请输入5-20个字符的用户名')
    # 判断密码是否是8-20个数字
    if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
        return HttpResponse('请输入8-20位的密码')

    user = authenticate(username=username, password=password)

    if user is not None:
        # 登录
        login(request, user)
        # 状态保持
        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(3600)
    else:
        return render(request, 'users/login.html', {'account_errmsg': '账号或密码错误'})

    return redirect('/')


# 退出登录
def login_out(request):
    logout(request)
    return redirect('/')